﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace T02TcpClient
{
    class TcpClient
    {
        static void Main(string[] args)
        {
            //套接字
            Socket client;
            //缓冲池
            byte[] buff = new byte[1024];
            //输入数据
            string input;
            //1，建立套接字信息
            //获取远程服务器的ip地址 测试时使用本机地址，实际测试可使用任意合法地址
            IPAddress remote = IPAddress.Parse("127.0.0.1");
            //端口范围1-65535,1-1024为系统占用
            IPEndPoint iep = new IPEndPoint(remote, 13000);
            //发生请求连接，服务端响应或出现异常
            try
            {
                //,建立（ipv4,流方式，tcp协议）的套接字
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //，与远程服务器连接
                client.Connect(iep);
            }
            catch (SocketException)
            {
                Console.WriteLine("无法连接至服务端。。。。。");
                return;
            }
            while (true)
            {
                input = Console.ReadLine();
                if (input == "exit") break;
                //发生数据
                client.Send(Encoding.ASCII.GetBytes(input));
                //接收应答
                int rec = client.Receive(buff);
                Console.WriteLine(Encoding.ASCII.GetString(buff, 0, rec));
            }
            Console.WriteLine("断开与服务器的连接...");
            client.Close();
        }
    }
}
